<script setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { get } from "@/request";
import { io, Socket } from "socket.io-client";
const value = ref("");
const person = ref([]);
let userId = ref(JSON.parse(localStorage.getItem("user"))._id || []);
let user = JSON.parse(localStorage.getItem("user"));
const newData = ref([]);
onMounted(() => {
  let socket = io("localhost:3000");
  get(`/users`, { query: { search_key: value } }).then((res) => {
    console.log(res, "user");
    person.value = user.groups[0].members;
  });
  getnew();
  socket.emit("login", userId);
  socket.on("user_id", (user_id) => {});
  get(`/getTalk2`).then((res) => {
    console.log(res);
    newData.value = res.data;
  });
});
let getmew = (event) => {
  if(event.key==="Enter"||event.keyCode===13){
    get(`/users`, { query: { search_key: value } }).then((res) => {
      person.value = user.groups[0].members;
    });
  }else{
    console.log(res, "22222");
  }
};
let getnew = (id) => {
  let datas = newData.value.filter(
      (item) =>
          (item.senderId == JSON.parse(localStorage.getItem("user"))._id &&
              item.senderId2 == id) ||
          (item.senderId2 == JSON.parse(localStorage.getItem("user"))._id &&
              item.senderId == id)
  );
  console.log(datas);
  datas = datas.reverse();
  if (datas.length !== 0) {
    if (datas[0].message) {
      return datas[0].message;
    } else {
      return "[消息卡片]";
    }
  } else {
    return "暂无聊天记录";
  }
};
const router = useRouter();
const show = (item) => {
  localStorage.setItem("user2", JSON.stringify(item));
  router.push("/Talk");
};
</script>

<template>
  <div class="w-100% h-20px flex items-center justify-between">
    <div class="flex">
      <img class="w-14 h-14 rounded-full" :src="user.avatar" alt="" />
      <p class="leading-10 ml-2">{{ user.name }}</p>
    </div>
    <div>
      <van-icon name="fire-o" size="32" class="mx-2" />
      <van-icon name="plus" size="32" class="mx-1" />
    </div>
  </div>
  <div class="mt-5">
    <van-search
        v-model="value"
        @keydown="getmew"
        placeholder="请输入搜索关键词"
    />
  </div>
  <div>
    <div
        v-for="items in person"
        :key="items._id"
        class="w-100% h-20 flex items-center justify-between"
        @click="show(items)"
    >
      <div>
        <div class="ml-2 flex items-center justify-between">
          <img class="w-14 h-14 rounded-full" :src="items.avatar" alt="" />
          <div class="ml-2">
            <p class="text-14px">{{ items.name }}</p>
            <p class="text-12px text-gray-400">{{ getnew(items._id) }}</p>
          </div>
        </div>
      </div>
      <div class="text-14px">{{}}</div>
    </div>
  </div>
</template>
<style scoped>
</style>